package com.aimashi.railwaytoolmanagesystem.utils;

import java.util.List;

import android.content.Context;

import com.aimashi.commonlib.util.StringUtil;
import com.aimashi.railwaytoolmanagesystem.bean.ScanCount;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

/**
 * 
 * @author zhaoys
 * 
 */
public class DatabaseScanCountUtil {
	// xutils
	private DbUtils db;

	public DatabaseScanCountUtil(Context context) {
		db = DbUtils.create(context);
	}

	/**
	 * 向数据库中添加数�?
	 * 
	 * @param entity
	 * @throws DbException
	 */
	public void add(ScanCount entity) {
		try {
			db.save(entity);
		} catch (DbException e) {
			e.printStackTrace();
			LogUtils.i("写卡出错");
		}
	}

	/**
	 * 通过Id查找对应的ScanCount
	 * 
	 * @param id
	 *            唯一标识Id
	 * @return
	 * @throws DbException
	 */
	public ScanCount findScanCountById(String epcNumber) {
		ScanCount entity = null;
		try {
			entity = db.findById(ScanCount.class, epcNumber); // db.findFirst(Selector.from(Parent.class).where("name","=","test"));
		} catch (DbException e) {
			LogUtils.i("查找保存epc标签出错");
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 查找ScanCount
	 * 
	 * @return
	 * @throws DbException
	 */
	public List<ScanCount> findAllScanCountByName(String searchValue) {
		List<ScanCount> entity = null;
		try {
			if (!StringUtil.isNull(searchValue)) {
				entity = db.findAll(Selector.from(ScanCount.class).orderBy(
						"date", true));
			} else {
				entity = db.findAll(Selector.from(ScanCount.class)
						.where("count", "like", "%" + searchValue + "%")
						.orderBy("date", true));
			}
		} catch (DbException e) {
			LogUtils.i("查找标签出错");
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 通过EpcNumber删除对应数据
	 * 
	 * @param id
	 * @throws DbException
	 */
	public void deleteScanCountByDate(String date) {
		try {
			db.deleteById(ScanCount.class, date);
		} catch (DbException e) {
			LogUtils.i("删除标签出错");
			e.printStackTrace();
		}
	}

	public void deleteScanCountAll() {
		try {
			db.deleteAll(ScanCount.class);
			db.dropTable(ScanCount.class);
		} catch (DbException e) {
			LogUtils.i("删除所有标签出错");
			e.printStackTrace();
		}
	}

	/**
	 * 更新标签信息
	 * 
	 * @param entity
	 *            实体
	 * @throws DbException
	 */
	public void UpdateScanCount(ScanCount entity) {
		deleteScanCountAll();
		add(entity);
	}

}
